package com.wyp168.juc.lock;

/**
 * @ClassName ReentrantReadWriteLockDemo002
 * @Description TODO
 * @Author wyp168
 * @Date 2022/9/22 22:26
 */

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockDemo002 {
    public static void main(String[] args) {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

        Produce produce = new Produce();
        //t1线程负责读Produce资源类中的属性值（200ms触发一次，共触发100次）
        new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                try {
                    readLock.lock();
//                    TimeUnit.MILLISECONDS.sleep(200);
                    System.out.println(produce.getCountNum());
                } finally {
                    readLock.unlock();
                }
            }
        }, "t1").start();

        //t2线程负责调用Produce资源类中的incrCountNum方法累加属性值（500ms触发一次、共触发50次）
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                try {
                    writeLock.lock();
//                    TimeUnit.MILLISECONDS.sleep(500);
                    produce.incrCountNum();
                } finally {
                    writeLock.unlock();
                }
            }
        }, "t2").start();
    }
}

class Produce {
    private volatile int countNum = 0;

    public int getCountNum() {
        return countNum;
    }

    public int incrCountNum() {
        return countNum++;
    }
}
